const { Article, Dictionary } = require('../models');
const { Op } = require('sequelize');
const dayjs = require('dayjs');

class ArticleService {
	static injector(ctn) {
		return [
			ctn.make('varal.app')
		]
	}
	constructor(app) {
		this.app = app;
	}

	async get(filter, page = 1, page_size = 20) {
		const { name, category_id, status } = filter;
		const where = {};
		if (name) where['name'] = { [Op.like]: `%${name}%` };
		if (!isNaN(category_id)) where['category_id'] = category_id;
		if (status) where['status'] = status;

		const { count: total, rows: data } = await Article.findAndCountAll({
			where,
			include: {
				model: Dictionary,
				as: 'category',
				attributes: ['name']
			},

			offset: (page - 1) * page_size,
			limit: page_size * 1,
			order: [
				['sort', 'desc'],
				['id', 'desc']
			]
		});

		return {
			data,
			total
		}
	}

	async info(where) {
		const article = await Article.findOne({
			where
		});

		if (article) await article.increment({ pv: 1 });

		return article;
	}

	async delete(id) {
		return await Article.destroy({
			where: {
				id: { [Op.in]: String(id).split(',') }
			}
		});
	}

	async save(params) {
		['create_time', 'update_time', 'delete_time'].forEach((d) => {
			delete params[d];
		});

		const { id } = params;

		if (id) {
			console.log(params);

			return await Article.update(params, {
				where: {
					id
				}
			})
		} else {
			return await Article.create(params);
		}
	}
}

exports = module.exports = ArticleService;
